package com.elem.dao.impl;

import com.elem.bean.Cart;
import com.elem.dao.CartDao;
import com.elem.util.DruidUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Collections;
import java.util.List;

public class CartDaoImpl implements CartDao {
    // 创建JdbcTemplate对象
    JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());

    @Override
    public List<Cart> listCart(Cart cart) throws Exception {
        try {
            // 根据用户的id查询购物车信息
            String sql = "select * from cart where userId = ?";
            List<Cart> cartList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Cart>(Cart.class), cart.getUserId());
            return cartList;
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public int saveCart(Cart cart) throws Exception {
        String sql = "insert into cart(foodId,businessId,userId,quantity) values(?,?,?,?)";
        int row = jdbcTemplate.update(sql, cart.getFoodId(), cart.getBusinessId(), cart.getUserId(), cart.getQuantity());
        return row;
    }

    @Override
    public int removeCart(Cart cart) throws Exception {
        String sql = "delete from cart  where userId = ? and foodId = ? and businessId = ?";
        int row = jdbcTemplate.update(sql, cart.getUserId(), cart.getFoodId(), cart.getBusinessId());
        return row;
    }

    @Override
    public int updateCart(Cart cart) throws Exception {
        String sql = "update cart set quantity = ? where userId = ? and foodId = ? and businessId = ?";
        int row = jdbcTemplate.update(sql, cart.getQuantity(), cart.getUserId(), cart.getFoodId(), cart.getBusinessId());
        return row;
    }
}
